# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)
class SyncsController < ApplicationController
  include SyncsHelper::Tests # this will soon be deprecated
  include SyncsHelper::Actions
  include SyncsHelper::Handshake
  include SyncsHelper::Request
  include SyncsHelper::NetSupport
  include SyncsHelper::Misc
  include UpgradesHelper

  # skip 3rd party authentication in this controller
  # skip_before_filter :login_from_cookie
  # skip_before_filter :login_required
  before_filter :authenticated?, :only => [:perform_sync, :up, :down]
  
  def perform_sync
    if request.xhr?
      # creates the semaphore quickly, so the async dump_sync_log don't get lost
      semaphore_deal
      
      # deletes log, so the async dump_sync_log don't get old stuff
      delete_log
      
      # start the script in the background. It will take care itself for duplications.
      # assumes that the User.current_user has the currently logged in user, which is 
      # requirement for any crud operation anyway
      script_file = File.join('lib', 'daemons', 'replicator.rb')
      processor, platform, *rest = RUBY_PLATFORM.split("-")
      runner_params = "'@logged_user=\"#{User.current_user.id}\"; load \"#{script_file}\"' -e #{ENV['RAILS_ENV']}"
      if platform != 'mswin32'
        system "./script/runner #{runner_params} &"
      else
        require 'win32/process'
        ruby_path = File.join(Dir.pwd, '..', 'ruby', 'bin', 'ruby.exe')
        Process.create(:app_name => "#{ruby_path} script\\runner #{runner_params}",
          :cwd => Dir.pwd,
          :creation_flags => Process::DETACHED_PROCESS )
      end
      
      render(:update) do |page|
        page['sync_button'].disabled = true # this will flag the dump_sync_log observer
        page['busy'].toggle
      end
    end
  end
  
  def dump_sync_log
    if request.xhr?
      log_file = File.join(RAILS_ROOT, $SYNC_CONFIG[:log_file])
      @buffer = ""
      begin
        File.open(log_file, 'r') do |f| 
          while line = f.gets
            @buffer << "#{line}<br/>\n"
          end
        end
      rescue => e
        logger.error "Something wrong reading log file #{log_file}, #{e.to_yaml}"
      end
      @has_finished = !File.exists?(File.join(RAILS_ROOT, $SYNC_CONFIG[:semaphore_file]))
      
      render(:update) do |page|
        page.replace_html('dump_log', @buffer) unless @buffer.empty?
        #page.visual_effect :highlight, 'dump_log'
        if @has_finished
          page['sync_button'].disabled = false
          page['busy'].toggle
          page.alert('Data Replication Finished.')
        end
      end
    end
  end
  
  def perform_upgrade
    if request.xhr?
      # creates the semaphore quickly, so the async dump_sync_log don't get lost
      upgrade_semaphore_deal
      
      # deletes log, so the async dump_sync_log don't get old stuff
      upgrade_delete_log
      
      # start the script in the background. It will take care itself for duplications.
      script_file = File.join('lib', 'daemons', 'replicator.rb')
      processor, platform, *rest = RUBY_PLATFORM.split("-")
      runner_params = "'load \"lib/daemons/upgrade.rb\"' -e #{ENV['RAILS_ENV']}"
      if platform != 'mswin32'
        system "./script/runner #{runner_params} &"
      else
        require 'win32/process'
        ruby_path = File.join(Dir.pwd, '..', 'ruby', 'bin', 'ruby.exe')
        Process.create(:app_name => "#{ruby_path} script\\runner #{runner_params}",
          :cwd => Dir.pwd )
      end
      
      render(:update) do |page|
        page['sync_button'].disabled = true # this will flag the dump_sync_log observer
        page['busy'].toggle
      end
    end
  end
  
  def dump_upgrade_log
    if request.xhr?
      log_file = File.join(RAILS_ROOT, 'log/upgrade.log')
      @buffer = ""
      begin
        File.open(log_file, 'r') do |f| 
          while line = f.gets
            @buffer << "#{line}<br/>\n"
          end
        end
      rescue => e
        logger.error "Something wrong reading log file #{log_file}, #{e.to_yaml}"
      end
      @has_finished = !File.exists?(File.join(RAILS_ROOT, 'log/upgrade.semaphore'))
      
      render(:update) do |page|
        page.replace_html('dump_log', @buffer) unless @buffer.empty?
        #page.visual_effect :highlight, 'dump_log'
        if @has_finished
          page['sync_button'].disabled = false
          page['busy'].toggle
          page.alert('Software Upgrade Finished. Restarting Application Recommended')
        end
      end
    end
  end
end
